<template>
  <tm-sheet  :padding="[20]" :margin="[0]"  v-for="(item,index) in DetailForms" :key="index">
    <view class="title">{{ item.name }}</view>
    <tm-sheet :padding="[10]" :margin="[0]">
      <tm-button :margin="[0]" :shadow="0" icon='tmicon-plus' text size="small" outlined label="新增" @click="showForm(item)"></tm-button>
    </tm-sheet>
    <scroll-view
      class="detailForm-wrap"
      :show-scrollbar="false"
      :scroll-x="true"
      :scroll-y="true"
    >
      <tm-row 
        :width="getTableWidth(item.tableData)" 
        :column="item.tableData.header.length"
        class="tableList"
      >
        <tm-col  
          :height='60' 
          v-for="(items,indexs) in item.tableData.header" 
          :key="indexs" 
          color="#f5f5f5"
        >
          {{ items.name }}
        </tm-col>
      </tm-row>
      <tm-row
        :width="getTableWidth(item.tableData)" 
        :column="item.tableData.header.length"
        class="tableList"
        v-for="(items,indexs) in item.tableData.data"
        :key="indexs"
      >
        <tm-col 
          v-for="(form,formIndex) in item.tableData.header"
          :key="formIndex"
          :height='0' 
        >
          <!-- <view v-if="form.name ==='操作'">
            <tm-button
              type="primary"
              size="small"
              @click="delTable(indexs,item)"
            >删除</tm-button>
          </view> -->
          {{ getFiledsText(items[form.field],form.field,item?.fields) }}
        </tm-col>
      </tm-row>
      <!-- <table>
        <thead>
          <tr>
            <th v-for="(items,indexs) in item.tableData.header" :key="indexs">
              {{ items.name}}
            </th>
          </tr>
        </thead>
      </table> -->
      <!-- <tm-table
        :table-data="item.tableData"
        :width="getTableWidth(item.tableData)"
        :cell-width="cellWidth"
        :stripe="stripe"
        :showHeader="showFixed"
        @row-click="delclick"
        :headerHeight="80"
      >
      </tm-table> -->
    </scroll-view>
  </tm-sheet>
  <tm-modal
    ref="calendarView" 
    title="新增表格"
    :height="900"
    :border="0"
    class="showModal"
    text
    linear="bottom"
    v-model:show="showPopup"
    @ok="ensureClick"
  >
    <tm-form ref="form" :margin="[0]"  :padding="[20]" :border="false" :model-value="primaryChangeData">
      <template v-for="(items,indexs) in formList" :key="indexs" >
        <tm-form-item
          v-if="items.valueType === '选择型'"
          :field="items.id"
          :show-error="false"
        >
          <slot>
            <view @click="popupPicker(items)"  class="flex flex-row flex-row-center-between time-select">
              <tm-text :userInteractionEnabled="false" :label="getText(primaryChangeData[items.id],items)"></tm-text>
              <tm-icon :userInteractionEnabled="false" :font-size="24" name="tmicon-angle-right"></tm-icon>
            </view>
          </slot>
        </tm-form-item>
        <tm-form-item
          :field="items.id"
          :show-error="false"
          v-else-if="items.valueType ==='用户型'"
        >
          <slot>
            <view>搜索</view>
          </slot>
        </tm-form-item>
        <tm-form-item
          :field="items.id"
          :show-error="false"
          v-else
        >
          <tm-input
            :transprent="true"
            :model-value="primaryChangeData[items.id]"
            :label="items.name"
            :placeholder="'请输入'+items.name"
            :border="1"
            :margin="[0]"
            :padding="[0]"
            @input="changeData(items,$event)"
          >
          </tm-input>
        </tm-form-item>
      </template>
    </tm-form>
  </tm-modal>
  <!-- 下拉选择 -->
  <tm-picker
    :columns="pickerlist"
    v-model:show="showPicker"
    @confirm="pickok"
  ></tm-picker>
</template>

<script lang="ts" setup>
import { kernel } from '@/ts/base';
import { computed, ref } from 'vue';
import OrgCtrl from '@/ts/controller'
const showPopup = ref(false)
type IProps = {
  formInfo: any,
  belongId:any
}
const props = defineProps<IProps>()
console.log(props,'props-detail')
const DetailForms = computed(() =>{
  const formData:{
    fields:any,
    data:any,
    node: {
      detailForms: any;
    }
  } = props.formInfo
  const arr:{
    id: any,
    name: any,
    tableData:any,
    data:[]
  }[] = []
  
  formData.node?.detailForms.forEach(async (element: { id: string | number; name: any; }) => {
    const _fdata = {
      id: element.id,
      name: element.name,
      tableData:{
        fields: {
          columns:getFileds(formData.fields[element.id])
        },
        header: getHeader(formData.fields[element.id]),
        data:[]
      },
      data:formData.data[element.id],
      fields: formData.fields[element.id],
    }
    arr.push(_fdata)
  })
  return arr
})
function getFileds(data:any) {
  const arr:any = ['id']
  data.forEach((items: { id: any; }) => {
    arr.push(items.id)
  })
  arr.push('operate')
  return arr
}
function getHeader(data:any) {
  const opts = {color: '#f5f5f5'}
  const arr:{field:any,name:any,opts:any}[] = [{field:'id',name:'唯一标识',opts:opts},{field:'name',name:'名称',opts:opts}]
  data.forEach((items: { id: any; name: any; }) => {
    arr.push({field: items.id,name:items.name,opts:opts})
  })
  // arr.push({\ield: 'operate',name:'操作',opts:opts})
  console.log(arr,'header')
  return arr
}
// function delclick(rowIndex:number,colIndex:number,value:string|number) {
//   console.log(rowIndex,'data')
//   console.log(colIndex)
//   console.log(value)
// }

const cellWidth = ref<number>(160)
function getTableWidth(data: { header: string | any[]; }) {
  return uni.$tm.u.torpx(data.header.length * cellWidth.value)
}
const formData = ref({})
const formList = ref({})    //表单渲染
const primaryChangeData = ref({})
function showForm(data:any) {
  showPopup.value = true
  formData.value = data
  formList.value = data.fields
  primaryChangeData.value = {}      
}

function getText(item:any,data:any) {
  let text:any = '请选择'
  data.lookups.forEach((element: { value: any; text: any; }) => {
    if(element.value === item){
      text = element.text
    }
  })
  return text
}
function getFiledsText(item:any,fieldId:any,data:any){
  const _value = item
  let _fields:any = {}
  data.forEach((item: { id: any; }) => {
    if(item.id === fieldId){
      _fields = item
    }
  })
  switch (_fields.valueType) {
    case '描述型':
    case '日期型':
    case '时间型':
    case '数值型':
      return _value ?? '-'
    case '选择型':
    case '分类型': {
      // console.log(_fields.lookups!.find(v => v.value === _value)?.text,'=====result')
      return _fields.lookups!.find((v: { value: any; }) => v.value === _value)?.text
    }
    case '用户型':
      return OrgCtrl.user.findShareById(_value)?.name
    case '附件型':
    case '引用型':
      if (!_value) return '-'
      try {
        const parsed = Array.isArray(_value) ? _value : JSON.parse(_value)
        return Array.isArray(parsed) ? parsed.map((d: any) => d.name) : '-'
      } catch (e) {
        return '-'
      }
    default:
      return _value ?? '-'
  }
  
}
const showPicker = ref(false)
const pickerlist = ref([])
const changeItems = ref({})
// 显示选择器
function popupPicker(data:any) {
  changeItems.value = data
  showPicker.value = !showPicker.value
  pickerlist.value = data.lookups
}
function pickok(modelValue:any){
  const selectData:{
    id:any,
    icon:any,
    parentId:any,
    text:any,
    value:any
  } = pickerlist.value[modelValue]
  primaryChangeData.value[changeItems.value.id] = selectData.value
}
async function ensureClick() {
  const arr:any = formData.value.tableData.data
  console.log(formData,'formData');
  
  await kernel.createThing(props.belongId, [], '').then((res) => {
    const after:any = { ...primaryChangeData.value,...res.data,...{name:formData.value.name}}
    formData.value.data.at(-1).after.push(after)
    arr.push(after)
   
  })
  console.log(arr,'arr')
  formData.value.tableData.data = [...arr]
}


function changeData(items:any,data:any) {
  primaryChangeData.value[items.id] = data
}

// function delTable(index:any,data:any){
//   console.log(data)
//   data.tableData.data.splice(index,1)
// }
</script>

<style lang="scss">
  .title{
    display:flex;
    align-items:center;
    font-size: 14px;
    font-weight: 500;
    margin: 10px 0;
    &:before{
      content: '';
      display:inline-block;
      width:3px;
      height: 16px;
      background:#366EF4;
      margin-right: 10px;
    }
  }
  .showModal{
    background-color: #fff;
  }
  .time-select{
    height: 33px;
    border: 1px solid rgba(230,230,230,1);
    border-radius: 6px;
    padding:0 5px;
    margin-top: 5px;
  }
  .tableList{
    font-size: 13px;
  }
</style>